package com.abe.mvp.view.activity;

import java.util.Timer;

import android.content.Intent;
import android.os.Bundle;

import com.abe.config.SerialPortConstants;
import com.abe.config.SettingParam;
import com.abe.config.StrengthtrainerSericalPortUtils;
import com.abe.mvp.contact.SerialPortContact;
import com.abe.mvp.contact.SocketContact;
import com.abe.mvp.model.bean.DeviceBean;
import com.abe.mvp.model.bean.SerialPortDataBean;
import com.abe.mvp.model.bean.SerialPortParseBean;
import com.abe.mvp.model.bean.SettingBean;
import com.abe.mvp.model.bean.exercise.ExerciseSTNodeBean;
import com.abe.mvp.presenter.SerialPortPresenterImp;
import com.abe.mvp.presenter.SocketPresenterImp;
import com.abe.utils.CRCChecker;
import com.abe.utils.JsonHelper;
import com.abe.utils.ThreadPoolUtils;

public class MainProgressActivity extends MainProgressViewActivity {
	/** 串口相关 */
	private SerialPortContact.Presenter serialPortPresenter;
	/** socket相关 */
	private SocketContact.Presenter socketPresenter;

	private SettingBean settingBean;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		serialPortPresenter = new SerialPortPresenterImp(this);
		socketPresenter = new SocketPresenterImp(this);
		serialPortPresenter
				.openSerialPort(SerialPortConstants.SerialPort_ttys3);
		settingBean = SettingParam.getSettingBean();
		isExercise = true;
		startSuccess();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isExercise = false;
		timer = null;
		if (serialPortPresenter != null) {
			serialPortPresenter.closeSerialPort();
			serialPortPresenter = null;
		}
		if (socketPresenter != null) {
			socketPresenter.closeSocket();
			socketPresenter = null;
		}
	}

	@Override
	public void sendSericalPortCommand(byte[] command) {
		serialPortPresenter.sendCommand(command);
		localCustomSendMessage(MAIN_REFRESH_SEND, JsonHelper.toJson(command));
	}

	@Override
	public void startSuccess() {
		timer = new Timer();
		exerciseStartTime = System.currentTimeMillis();
		timer.schedule(task, 1000, 1000);
		/** 启动读数据线程 */
		ThreadPoolUtils.execute(new TransmissionThread());
	}

	@Override
	public void stopSuccess() {
		timer.cancel();
		exerciseStopTime = System.currentTimeMillis();
		groupBean.setKeepTime((int) (exerciseStopTime - exerciseStartTime));
		/** 跳转展示运动信息 */
		Intent intent = getIntent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("exercise", groupBean);
		intent.putExtras(bundle);
		setResult(RESULT_OK, intent);
		back();
	}

	class TransmissionThread implements Runnable {

		@Override
		public void run() {
			/** 读命令 */
			byte[] READ_DATA = CRCChecker
					.getSendBuf(StrengthtrainerSericalPortUtils.READ_DATA);
			while (isExercise) {
				try {
					/** 发送读命令 */
					if (serialPortPresenter != null) {
						serialPortPresenter.sendCommand(READ_DATA);
						localCustomSendMessage(MAIN_REFRESH_SEND,
								JsonHelper.toJson(READ_DATA));
					}
					/** 等待时间 */
					Thread.sleep(readDataRate);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/********************************* 串口相关 **************************************/
	@Override
	public void onReceiveData(Boolean isSuccess, SerialPortDataBean data) {
		if (isSuccess) {

			SerialPortParseBean parseBean = StrengthtrainerSericalPortUtils
					.parse(data);
			if (parseBean.isVerifyStatus()) {
				if (parseBean.getUseType() == 0) {
					/** 读操作返回成功 */
					DeviceBean deviceBean = parseBean.getReadData();
					currentCustomHeight = deviceBean.getHeight();
					if (customMaxHeight < currentCustomHeight) {
						customMaxHeight = currentCustomHeight;
					}
					refreshCount();
					/** 更新进度条 */
					localCustomSendEmptyMessage(MAIN_REFRESH_PROGRESS);
					currentCustomWeight = deviceBean.getWeight();
					if (oldCustomWeight != currentCustomWeight) {
						/** 重量重新设置节点 */
						ExerciseSTNodeBean nodeBean = new ExerciseSTNodeBean();
						nodeBean.setNodeWeight(currentCustomWeight);
						nodeBean.setNodeCount((currentCount > 0) ? currentCount - 1
								: 0);
						oldCustomWeight = currentCustomWeight;
						nodeBeans.add(nodeBean);
					}
					/** 更新重量 */
					localCustomSendEmptyMessage(MAIN_REFRESH_WEIGHT);
					/** 刷新锻炼数据 */
					refreshExerciseGroupData(currentCount);
					/** 更新卡路里 */
					localCustomSendEmptyMessage(MAIN_REFRESH_KAL);
					localCustomSendMessage(MAIN_REFRESH_RECEIVE, "最大："
							+ customMaxHeight + "---实时：" + currentCustomHeight);
				}
			} else {
				/** 数据校验失败 */
			}
		}
	}

	/********************************** socket相关 *************************************/

	@Override
	public void onSocketError(String errorMsg) {
		/** socket异常 */
		if (socketPresenter != null) {
			/** 开启socket轮询来一直请求连接socket */
			socketPresenter.openSocket(settingBean.getSocketIp(),
					settingBean.getSocketPort());
		}
	}

}
